import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import useUserStore from "@/store/modules/user";
import axios, { AxiosError, AxiosResponse, InternalAxiosRequestConfig } from "axios";
import { app } from '@/main';
import { ElMessage } from "element-plus";

const instance = axios.create({
  // 如果要测试mock注释掉baseURL
  // baseURL: '/api',
  baseURL: import.meta.env.VITE_API_BASE_URL,
  timeout: 10000,
  headers: {"Authorization": "Basic c3Rhcms6MTIzNDU2Nzg5"}
})
instance.interceptors.request.use((config:InternalAxiosRequestConfig<any>) => {
  const userStore = useUserStore()
  NProgress.start()
  if(userStore.access_token !== 'undefined') {
    config.headers['Access-Token'] = userStore.access_token
  }
  return config
})

instance.interceptors.response.use((response: AxiosResponse): any => {
    if(response.data.status === 200) {
      ElMessage.success(response.data.message)
    } else {
      ElMessage.error(response.data.message)
      if(response.data.status === 1011) {
        console.log('logout', app.config.globalProperties.$router)
        app.config.globalProperties.$router.push('/login')
      }
    }
    NProgress.done()

  return { code: response.data.status, data: response.data.data }
},(error: AxiosError) => {
  console.log(error);
  NProgress.done()

})

export default instance;